// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
    env: 'car-test-1jjya',
    traceUser: true
})
const db = cloud.database()
const cars = db.collection('cars')
const _ = db.command
    // 云函数入口函数
exports.main = async(event, context) => {
    const wxContext = cloud.getWXContext()
    const openId = wxContext.OPENID
    event.openid = openId
    return addcar(event)
}

async function addcar(event) {
    console.log(event)

    var isExist = await cars.where(_.and([{ //  查询当前openid下是否有这辆车的名字
                openid: event.openid
            },
            {
                name: event.name
            }
        ])).get()
        // console.log(isExist)
    if (isExist.data.length == 0) { // 表示当前没有这辆车
        var result = await cars.add({ data: event })
            // console.log(result)
        return 'success'
    } else {
        return 'isExist'
    }
    // if (result.stats.updated) { // 判断是否更新成功
    //     return 'success'
    // } else {
    //     return 'error'
    // }

}